#include "global_val.h"
#include "uart.h"
#include "sql.h"
#include "pthread_init_destroy.h"
#include "websocketserver.h"
#include "getsysinfo.h"
#include "dev_related.h"
#include "alarm_task_list.h"

static pthread_t g_tid[1024];
static int g_tid_sum = 0;

/*********************************************************************
 * @fn      Pthread_creat_init
 *
 * @brief   所有线程初始化函数 线程id放在全局数组 g_tid 中 g_tid_sum为
 *          线程个数
 *
 * @param   none
 *
 * @return  none
 */
void Pthread_creat_init(int websocket_server_port)
{
	int ret;

	//串口发送 发送的过程中顺便判断消息队列上是否有消息需要进行发送
	ret = pthread_create(&g_tid[g_tid_sum++], NULL, Pthread_UART_Send, NULL);
	if(ret!=0)
	{
		sys_error_num("pthread_create", ret);
	}

	//串口接收
	ret = pthread_create(&g_tid[g_tid_sum++], NULL, Pthread_UART_Receive, NULL);
	if(ret!=0)
	{
		sys_error_num("pthread_create", ret);
	}

	//串口接收队列中的数据处理
	ret = pthread_create(&g_tid[g_tid_sum++], NULL, Pthread_UART_Receive_Data_Handle, NULL);
	if(ret!=0)
	{
		sys_error_num("pthread_create", ret);
	}

	ret = pthread_create(&g_tid[g_tid_sum++], NULL, client_service, NULL);
	if(ret!=0)
	{
		sys_error_num("pthread_create", ret);
	}

	ret = pthread_create(&g_tid[g_tid_sum++], NULL, server_accept_init, (void *)websocket_server_port);
	if(ret!=0)
	{
		sys_error_num("pthread_create", ret);
	}

	//发送更新数据命令 防止设备无响应 网页状态变化
    ret = pthread_create(&g_tid[g_tid_sum++], NULL, WebSocket_msg_listen, NULL);
	if(ret!=0)
	{
		sys_error_num("pthread_create", ret);
	}

    //ret = pthread_create(&g_tid[g_tid_sum++], NULL, pthread_sys_cpu_updata, NULL);
	if(ret!=0)
	{
		sys_error_num("pthread_create", ret);
	}

    //ret = pthread_create(&g_tid[g_tid_sum++], NULL, pthread_sys_ram_uptime_update, NULL);
	if(ret!=0)
	{
		sys_error_num("pthread_create", ret);
	}

    //ret = pthread_create(&g_tid[g_tid_sum++], NULL, pthread_sys_rootinfo_update, NULL);
	if(ret!=0)
	{
		sys_error_num("pthread_create", ret);
	}

	//设备列表信息发送
    //ret = pthread_create(&g_tid[g_tid_sum++], NULL, Get_Dev_Status_list, NULL);
	// if(ret!=0)
	// {
		// sys_error_num("pthread_create", ret);
	// }
	
	ret = pthread_create(&g_tid[g_tid_sum++], NULL, pthread_get_clock_msg, NULL);
	if(ret!=0)
	{
		sys_error_num("pthread_create", ret);
	}
	
	ret = pthread_create(&g_tid[g_tid_sum++], NULL, pthread_del_alarm_task, NULL);
	if(ret!=0)
	{
		sys_error_num("pthread_create", ret);
	}
	
	//设备列表配置信息发送 包含状态信息
    ret = pthread_create(&g_tid[g_tid_sum++], NULL, Get_Dev_Cfg_list, NULL);
	if(ret!=0)
	{
		sys_error_num("pthread_create", ret);
	}
	
	//更新task_list链表中节点的信息
	ret = pthread_create(&g_tid[g_tid_sum++], NULL, alarm_task_list_update, NULL);
	if(ret!=0)
	{
		sys_error_num("pthread_create", ret);
	}
}

/*********************************************************************
 * @fn      Pthread_join_init
 *
 * @brief   等待所有线程运行结束
 *
 * @param   none
 *
 * @return  none
 */
void Pthread_join_init(void)
{
	int i;
	for(i=0; i<g_tid_sum; ++i)
	{
		pthread_join(g_tid[i], NULL);
	}
}
